# Create your views here.
from django.shortcuts import render_to_response
from models import Event
from forms import EventForm
from django.template.context import RequestContext
from django.contrib.auth.decorators import login_required
from django.views.decorators.http import require_GET, require_POST
from django.contrib import messages
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse

@require_GET
@login_required(redirect_field_name=None)
def index(request):
    return render_to_response("events/index.html", { 'events':Event.objects.all(), 'form':EventForm() }, context_instance=RequestContext(request))

@require_POST
@login_required(redirect_field_name=None)
def create(request):
    form = EventForm(request.POST)
    if form.is_valid() :
        event = form.save(commit = False )
        event.owner = request.user
        event.save()
        event.participants.add( request.user )
        messages.success( request, '<strong>Success!</strong> Event was successfully created' )
    else :
        errorMessage = '<dl class="dl-horizontal">'
        for error in form.errors :
            for message in form.errors[error] :
                errorMessage += '<dt>' + error + '</dt><dd>' + message + '</dd>'
        errorMessage += '</dl>'
        messages.error(request, errorMessage )
    return HttpResponseRedirect( reverse('event_index') )

def view(request, id):
    return render_to_response("events/detail.html", { 'event':Event.objects.get(pk=id) }, context_instance=RequestContext(request))

@require_POST
@login_required(redirect_field_name=None)
def delete(request, id):
    event = Event.objects.get(pk=id)
    if event :
        event.delete()
        messages.info( request, '<strong>Success!</strong> You have successfully deleted the event!')
    return HttpResponseRedirect( reverse('event_index') );

@require_POST
@login_required(redirect_field_name=None)
def join(request, id):
    event = Event.objects.get(pk=id)
    event.participants.add( request.user )
    messages.success(request, '<strong>Success!</strong> You have joined the event')
    return HttpResponseRedirect( reverse('event_view', args=(id,) ) )

@require_POST
@login_required(redirect_field_name=None)
def leave(request, id):
    event = Event.objects.get(pk=id)
    event.participants.remove( request.user )
    messages.success(request, '<strong>Success!</strong> You have left the event')
    return HttpResponseRedirect( reverse('event_view', args=(id,) ) )